#!/usr/bin/env python
# -*- coding: utf-8 -*-

#TODO: use of decorators do build a log ??
DEBUG = False

from mechanize import Browser, FormNotFoundError, LinkNotFoundError
from re import compile

class Connection:
    source=None
    title=None
    url=None
    info=None
    loginok=False

    def __init__(self, server, user_agent, uname, upass):
        self.user_agent = user_agent
        
        self.Browser=Browser()
        self.setHeaders()

        self.server=server
        if self.server[-1:]!='/':
            self.server=self.server+'/'

        self.uname=uname
        self.upass=upass


    def setHeaders(self):
        self.Browser.addheaders = [
                ('User-Agent', self.user_agent),
                ]
        if DEBUG:
            print "="*79
            print "set Headers"
            print self.user_agent
            print "="*79


    def Login(self):
        print u"»Login on server...", self.server
        url=self.server+'login.php'
        print url

        self.Browser.open(url)
        self.Browser.select_form(name='snd')

        for ctr in self.Browser.form.controls:
            if ctr.type=='text':
                uname=ctr.name
            elif ctr.type=='password':
                upass=ctr.name

        self.Browser[uname]=self.uname
        self.Browser[upass]=self.upass
        
        if DEBUG:
            print self.Browser.form

        resp = self.Browser.submit() 

        try:
            self.Browser.select_form(name='snd')
        except FormNotFoundError, e:
            if self.Browser.geturl()==self.server+'dorf1.php':
                self.source = resp.read()
                self.loginok = True
                print u"Login ok!!!"
                return True

        self.source = None
        self.loginok = False
        print u"Error on Login!!!"
        return False


    def Logout(self):
        print u"»Logout on server",
        resp = self.MyBrowser('logout.php',0,'url')
        if resp:
            self.source=None
            self.loginok=False
            print u"Logout OK!!!"
            return True

        print u"Can't logout on server."
        self.source = None
        self.loginok = False


    def MyBrowser(self, link, nr=0, t="txt"):
        if DEBUG:
            print "I'm in url", self.url
            print "Want to go to (%s) (%i) (%s)" % (link,nr,t)

        try:
            if t=="txt":
                resp = self.Browser.follow_link(text_regex=compile(link), nr=nr)
            elif t=="url":
#                resp = self.Browser.follow_link(url=link,nr=nr)
                resp = self.Browser.follow_link(url_regex=link,nr=nr)

        except LinkNotFoundError,e:
            return False

        self.url= resp.geturl()
        self.info=resp.info()  # headers
        self.source=resp.read()  # body
        resp.close()

        return True
        
